/**
 * Copyright (C) <2023> <Boundivore> <boundivore@foxmail.com>
 * <p>
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Apache License, Version 2.0
 * as published by the Apache Software Foundation.
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * Apache License, Version 2.0 for more details.
 * <p>
 * You should have received a copy of the Apache License, Version 2.0
 * along with this program; if not, you can obtain a copy at
 * http://www.apache.org/licenses/LICENSE-2.0.
 */
/**
 * 监控页
 * @author Tracy
 */
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Table, Card, Row, Col, Flex, Space, Empty } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import useStore from '@/store/store';
import { config, monitorItems } from '@/components/charts/config';
import { JobNameComponent, TimerComponent } from '@/components/charts/params';
import useCurrentCluster from '@/hooks/useCurrentCluster';
import usePrometheusStatus from '@/hooks/usePrometheusStatus';
import ContainerCard from '@/components/containerCard';
import { RenderConfig } from '@/components/charts/renderConfig';
import APIConfig from '@/api/config';
import RequestHttp from '@/api';
import { ServiceComponentSummaryVo } from '@/api/interface';
interface ItemStyle {
	Id: string;
	ServiceName: string;
	ComponentName: string;
}

const Monitor = () => {
	const { t } = useTranslation();
	const { jobName, instance } = useStore();
	const [activeComponent, setActiveComponent] = useState(monitorItems[0].Id);
	const [serviceTable, setServiceTable] = useState<ItemStyle[]>([]);
	const { hasPrometheus } = usePrometheusStatus();
	const { clusterComponent, selectCluster } = useCurrentCluster();

	const serviceColumn: ColumnsType<ItemStyle> = [
		// {
		// 	title: t('service.serviceName'),
		// 	dataIndex: 'ServiceSummary',
		// 	render: text => <a>{text?.ServiceName}</a>
		// },
		{
			title: t('service.componentName'),
			dataIndex: 'Id',
			render: text => <span>{text}</span>
		}
	];

	const rowClassName = (record: ItemStyle) => {
		return activeComponent === record.Id ? 'bg-[#f0fcff]' : '';
	};
	const getInfo = async () => {
		const apiList = APIConfig.componentList;
		const params = {
			ClusterId: selectCluster
		};
		const data = await RequestHttp.get(apiList, { params });
		const {
			Data: { ServiceComponentSummaryList }
		} = data;

		const tableData = monitorItems;
		ServiceComponentSummaryList.map((item: ServiceComponentSummaryVo) => {
			const serviceName = item.ServiceSummary.ServiceName;

			item.ComponentSummaryList.forEach(component => {
				// // 仅在 ComponentName 不包含 "client" 时添加到结果中
				// if (!/client/i.test(component.ComponentName.toLowerCase())) {
				// 	tableData.push({
				// 		ServiceName: serviceName,
				// 		ComponentName: component.ComponentName,
				// 		Id: `${serviceName}-${component.ComponentName}`
				// 	});
				// }
				let componentName = component.ComponentName;

				// 过滤掉包含 "client" 的组件名称
				if (/client/i.test(componentName.toLowerCase())) return;

				// 如果名称包含类似 "NameNode1" 或 "NameNode2" 的格式，将数字去掉，统一为 "NameNode"
				componentName = componentName.replace(/(\d+)$/, '');

				// 检查结果中是否已包含相同 ServiceName 和 ComponentName 的项，避免重复
				if (!tableData.some(item => item.ServiceName === serviceName && item.ComponentName === componentName)) {
					tableData.push({
						ServiceName: serviceName,
						ComponentName: componentName,
						Id: `${serviceName}-${componentName}`
					});
				}
			});

			return tableData;
		});

		setServiceTable(tableData);
	};

	useEffect(() => {
		selectCluster && getInfo();
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [selectCluster]);

	return (
		<ContainerCard>
			{selectCluster ? (
				<>
					<Flex justify="space-between">
						{clusterComponent}
						<Space size="large">
							{selectCluster && activeComponent && (
								<JobNameComponent clusterId={selectCluster} activeComponent={activeComponent} />
							)}
							<TimerComponent />
						</Space>
					</Flex>
					<Row gutter={24} className="mt-[20px]">
						<Col span={6}>
							<Card className="data-light-card">
								<Table
									className="mt-[20px] cursor-pointer"
									rowKey="ComponentName"
									columns={serviceColumn}
									dataSource={serviceTable}
									onRow={record => {
										return {
											onClick: () => {
												setActiveComponent(record.Id);
											}
										};
									}}
									pagination={false}
									rowClassName={rowClassName}
								/>
							</Card>
						</Col>
						<Col span={18}>
							<Card className="data-light-card" title={activeComponent}>
								{hasPrometheus ? (
									selectCluster && jobName && instance && config[activeComponent] ? (
										<RenderConfig config={config[activeComponent]} selectCluster={selectCluster} />
									) : (
										<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
									)
								) : (
									<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={<span>{t('noPrometheus')}</span>}></Empty>
								)}
							</Card>
						</Col>
					</Row>
				</>
			) : (
				<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
			)}
		</ContainerCard>
	);
};
export default Monitor;
